import datetime
import os


class FileGeneratorHtml:
    def __init__(self, base_dir="D:\\test", template=None):
        """
        初始化文件生成器

        :param base_dir: 文件保存的根目录
        :param template: 文件内容模板，支持 {key} 格式的占位符
        """
        self.base_dir = base_dir
        self.template = template or """
{{% extends 'dms_console.html' %}}

{{% block maincontent %}}
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header layuiadmin-card-header-auto">
                <form class="layui-form">
                    <div class="layui-form-item">
                        {{# HTML-查询-业务字段 #}}
                        
                        
                        <div class="layui-inline">
                            <label class="layui-form-label">责任人</label>
                            <div class="layui-input-inline" style="width: 120px;">
                                <input type="text" id="principal" name="principal" placeholder="责任人"
                                       class="layui-input"
                                       lay-affix="clear">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">上线日期</label>
                            <div class="layui-input-inline" style="width: 150px;">
                                <select id="online_date" name="online_date" lay-search>
                                    <option value="">直接或搜索选择</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">创建人</label>
                            <div class="layui-input-inline" style="width: 120px;">
                                <input type="text" id="created_by" name="created_by" placeholder="创建人"
                                       class="layui-input"
                                       lay-affix="clear">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn layuiadmin-btn-list" lay-submit
                                    lay-filter="formSearch"
                                    id="btnSearch">
                                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>搜索
                            </button>
                            <button class="layui-btn layuiadmin-btn-list layui-btn-primary" type="reset"
                                    id="customReset">
                                <i class="layui-icon layui-icon-set-sm layuiadmin-button-btn"></i>重置
                            </button>
                            <button class="layui-btn layuiadmin-btn-list layui-btn-normal"
                                    id="exportAllBtn"
                                    lay-submit lay-filter="export">
                                <i class="layui-icon layui-icon-export layuiadmin-button-btn"></i>导出
                            </button>
                            <button class="layui-btn layui-btn-normal layuiadmin-btn-list" type="button"
                                    id="addBtn">
                                <i class="layui-icon layui-icon-add-circle-fine layuiadmin-button-btn"></i>添加
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="layui-card-body">
                <table id="{api_name}TableId" lay-filter="{api_name}TableLayFilter"></table>
            </div>
        </div>
    </div>
{{% endblock %}}

{{% block script %}}
    <!-- 添加/编辑表单模板 -->
    <script type="text/html" id="{api_name}FormId">
        <form class="layui-form" lay-filter="{api_name}FormLayFilter" style="padding:20px">
            <input type="hidden" name="{primary_key}">
            {{# HTML-新增模板-业务字段 #}}
            
            
            <div class="layui-form-item">
                <label class="layui-form-label">责任人</label>
                <div class="layui-input-inline">
                    <input type="text" name="principal" id="principal" lay-verify="required"
                           placeholder="请输入责任人"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">上线日期</label>
                <div class="layui-input-inline">
                    <select name="online_date_template" id="online_date_template" lay-verify="required" lay-search>
                        <option value="">直接选择或搜索选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述或备注</label>
                <div class="layui-input-inline">
                    <textarea name="comment" id="comment" placeholder="请输入你想描述或备注的信息(非必填)"
                              class="layui-textarea" style="width:300px;"></textarea>
                </div>
            </div>
            <div class="layui-form-item" style="width: 146px; margin: 0 auto;">
                <div class="layui-input-inline">
                    <button class="layui-btn" id="submitBtn" lay-submit lay-filter="formSubmit">提交</button>
                    <button type="button" class="layui-btn" id="closeWindowsBtn">关闭</button>
                </div>
            </div>
        </form>
    </script>

    <!-- 操作列模板 -->
    <script type="text/html" id="{api_name}BarOption">
        <a class="layui-btn layui-btn-xs layui-bg-red" lay-event="delete">删除</a>
    </script>

    <script>
        layui.use(['table', 'layer', 'form'], function () {{
            // var $ = layui.jquery;
            var $ = layui.$;
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;

            // 初始化时加载下拉框数据
            $.ajax({{
                url: '/dms/api/get{class_name}OnlineDate',
                type: 'GET',
                dataType: 'json',
                success: function (res) {{
                    if (res.code === 0) {{
                        var html = '<option value="">直接或搜索选择</option>';
                        $.each(res.data, function (index, item) {{
                            html += '<option value="' + item.online_date + '">' + item.online_date + '</option>';
                        }});
                        $('#online_date').html(html);
                        $('#online_date_template').html(html);
                        // 重新渲染表单
                        form.render('select');
                    }}
                }},
                error: function () {{
                    layer.msg('数据加载失败');
                }}
            }});

            // 初始化表格 - 国际化
            var {api_name}TableIns = table.render({{
                elem: '#{api_name}TableId',
                url: '/dms/api/{api_name}',
                method: 'get',
                page: true,
                css: [ // 设置单元格样式
                    // 取消默认的溢出隐藏，并设置适当高度
                    '.layui-table-cell{{height: 50px; line-height: 40px;}}',
                    '.layui-table-cell .layui-colorpicker{{width: 38px; height: 38px;}}',
                    '.layui-table-cell select{{height: 36px; padding: 0 5px;}}'
                ].join(''),
                height: 650,
                cols: [[
                    {{field: '{primary_key}', title: 'ID', width: 80, align: 'center', fixed: 'left'}},
                    // HTML - 初始化表格 - 业务字段
                    
                    
                    {{field: 'principal', title: '责任人', width: 130, edit: 'text', align: 'center'}},
                    {{field: 'online_date', title: '上线日期', width: 110, edit: 'text', align: 'center'}},
                    {{field: 'comment', title: '备注', width: 110, edit: 'text', align: 'left'}},
                    {{field: 'last_updated_by', title: '更新人IP', width: 120, align: 'left'}},
                    {{field: 'last_update_date', title: '更新时间', width: 170, align: 'left'}},
                    {{field: 'created_by', title: '创建人IP', width: 120, align: 'left'}},
                    {{field: 'creation_date', title: '创建时间', width: 170, align: 'left'}},
                    {{
                        fixed: 'right',
                        title: '操作',
                        width: 100,
                        minWidth: 70,
                        align: 'center',
                        toolbar: '#{api_name}BarOption'
                    }}
                ]]
            }});

            // 绑定表单提交事件。点击搜索按钮，提交表单
            form.on('submit(formSearch)', function (data) {{
                {api_name}TableIns.reload({{
                    where: data.field,
                    page: {{curr: 1}}
                }});
                return false;
            }});

            // 监听单元格编辑
            table.on('edit({api_name}TableLayFilter)', function (obj) {{
                const field = obj.field;
                const value = obj.value;
                const row = obj.data;
                if (field === 'language' && value !== 'zh_CN' && value !== 'en_US') {{
                    layer.msg('更新失败，language应该为“zh_CN”或者“en_US”，不能为其他值！', {{
                        icon: 0, // 使用 icon:0 显示为感叹号图标
                        skin: 'layui-layer-danger', // 使用 layui-layer-molv 作为警告风格背景
                        time: 3000 // 显示时间为3秒
                    }});
                    {api_name}TableIns.reload();
                }} else {{
                    // 发送更新请求
                    $.ajax({{
                        url: '/dms/api/{api_name}Update',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({{
                            id: row.{primary_key},
                            field: field,
                            value: value
                        }}),
                        success: function (res) {{
                            if (res.status !== 'success') {{
                                layer.msg('更新失败: ' + res.message);
                                {api_name}TableIns.reload();
                            }} else {{
                                layer.msg('更新成功!');
                                {api_name}TableIns.reload();
                            }}
                        }}
                        , error: function (xhr, status, error) {{
                            layer.msg('Error: ' + xhr.status + ' ' + xhr.statusText);
                            {api_name}TableIns.reload();
                        }}
                    }});
                }}
            }});

            // 添加按钮事件
            $('#addBtn').click(function () {{
                var index = layer.open({{
                    type: 1,
                    title: '添加 {business_type} 信息',
                    area: '475px',
                    content: $('#{api_name}FormId').html()
                }});
                form.render();

                // 初始化时加载下拉框数据
                $.ajax({{
                    url: '/dms/api/get{class_name}OnlineDate',
                    type: 'GET',
                    dataType: 'json',
                    success: function (res) {{
                        if (res.code === 0) {{
                            var html = '<option value="">直接或搜索选择</option>';
                            $.each(res.data, function (index, item) {{
                                html += '<option value="' + item.online_date + '">' + item.online_date + '</option>';
                            }});
                            $('#online_date_template').html(html);
                            // 重新渲染表单
                            form.render('select');
                        }}
                    }},
                    error: function () {{
                        layer.msg('数据加载失败');
                    }}
                }});

                // 关闭窗口按钮
                $('#closeWindowsBtn').click(function () {{
                    layer.close(index); // 关闭加载层
                }});
                // 表单提交事件
                form.on('submit(formSubmit)', function (data) {{
                    var method = data.field.{primary_key} ? 'PUT' : 'POST';
                    var url = data.field.{primary_key} ? '/dms/api/{api_name}/' + data.field.{primary_key} : '/dms/api/add{class_name}';
                    $.ajax({{
                        url: url,
                        type: method,
                        contentType: 'application/json',
                        data: JSON.stringify(data.field),
                        success: function (res) {{
                            if (res.status === 'error') {{
                                layer.msg(res.message);
                            }} else {{
                                layer.closeAll();
                                layer.msg('操作成功');
                                {api_name}TableIns.reload();
                            }}
                        }},
                        error: function (xhr) {{
                            layer.msg('操作失败: ' + xhr.responseJSON.msg);
                        }}
                    }});
                    return false;
                }});
            }});

            // 表格操作事件 触发单元格工具事件
            table.on('tool({api_name}TableLayFilter)', function (obj) {{
                var data = obj.data;
                if (obj.event === 'delete') {{
                    layer.confirm('确定删除吗？', function (index) {{
                        $.ajax({{
                            url: '/dms/api/{api_name}/' + data.{primary_key},
                            type: 'DELETE',
                            success: function (res) {{
                                if (res.status === 'error') {{
                                    layer.msg(res.message);
                                }} else {{
                                    layer.closeAll();
                                    layer.msg('已删除');
                                    {api_name}TableIns.reload();
                                }}
                            }}
                        }});
                    }});
                }}
            }});

            // 数据导出
            form.on('submit(export)', function (data) {{
                layer.confirm('导出当前查询条件的所有数据吗？', function (index) {{
                    layer.close(index);
                    layer.msg('正在生成文件...', {{icon: 16, time: 1500}});
                    // 创建隐藏的iframe实现下载
                    setTimeout(function () {{
                        // HTML-数据导出-业务字段-定义变量
                        
                        
                        var principal2 = $('#principal').val();
                        var online_date2 = $('#online_date').val();
                        var created_by2 = $('#created_by').val();

                        var exportUrl = '/dms/api/export{class_name}?';
                        
                        // HTML-数据导出-业务字段-拼接到URL
                        
                        
                        exportUrl += 'principal' + '=' + encodeURIComponent(principal2) + '&';
                        exportUrl += 'online_date' + '=' + encodeURIComponent(online_date2) + '&';
                        exportUrl += 'created_by' + '=' + encodeURIComponent(created_by2);

                        var iframe = document.createElement('iframe');
                        iframe.style.display = 'none';
                        iframe.src = exportUrl;
                        document.body.appendChild(iframe);

                        // 下载完成后移除iframe
                        setTimeout(function () {{
                            document.body.removeChild(iframe);
                            layer.msg('导出成功！');
                        }}, 2000);
                    }}, 1500);
                }});
                return false;
            }});

        }});
    </script>
{{% endblock %}}
"""
        # 确保目录存在
        if not os.path.exists(self.base_dir):
            os.makedirs(self.base_dir)

    def generate_files(self, data_list):
        """
        批量生成文件

        :param data_list: 字典列表，每个字典包含 file_name 和其他用于模板的字段
        """
        file_name = ""
        for data in data_list:
            if 'file_name' not in data:
                print("警告：缺少 file_name 字段，跳过该条目")
                continue
            date_string = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
            # 创建多层文件夹（自动处理父目录，并忽略已存在错误）
            os.makedirs(os.path.join(self.base_dir, date_string), exist_ok=True)
            # data['file_name'] = date_string + "-" + data['file_name']
            file_path = os.path.join(self.base_dir, date_string, data['file_name'])

            try:
                # 使用字典展开填充模板
                content = self.template.format(**data)
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                print(f"✅ 已生成文件: {file_path}")
            except KeyError as e:
                print(f"❌ 模板中使用的变量 {e} 在数据中不存在，文件 {data['file_name']} 生成失败。")
            except Exception as e:
                print(f"❌ 写入文件失败 {file_path}: {e}")


# 示例使用
if __name__ == "__main__":
    # 模拟数据
    data_list = [
        {"序号": "1", "model_key": "lookup", "key": "lookup_classify", "dao_name": "lookup_classify_dao",
         "file_name": "lookup_classify.html", "class_name": "LookupClassify", "api_name": "lookupClassify",
         "primary_key": "lookup_classify_id", "business_type": "Lookup Classify", "excel_title": "Lookup Classify"}
        , {"序号": "2", "model_key": "lookup", "key": "lookup_item", "dao_name": "lookup_item_dao",
           "file_name": "lookup_item.html", "class_name": "LookupItem", "api_name": "lookupItem",
           "primary_key": "lookup_item_id", "business_type": "Lookup Item", "excel_title": "Lookup Item"}
        , {"序号": "3", "model_key": "lookup", "key": "lookup_delete", "dao_name": "lookup_delete_dao",
           "file_name": "lookup_delete.html", "class_name": "LookupDelete", "api_name": "lookupDelete",
           "primary_key": "lookup_delete_id", "business_type": "Lookup手工删除", "excel_title": "Lookup Delete"}
        , {"序号": "4", "model_key": "lookup", "key": "lookup_disable", "dao_name": "lookup_disable_dao",
           "file_name": "lookup_disable.html", "class_name": "LookupDisable", "api_name": "lookupDisable",
           "primary_key": "lookup_disable_id", "business_type": "Lookup手工失效", "excel_title": "Lookup Disable"}
        ,
        {"序号": "5", "model_key": "catalog", "key": "catalog", "dao_name": "catalog_dao", "file_name": "catalog.html",
         "class_name": "Catalog", "api_name": "catalog", "primary_key": "catalog_id", "business_type": "菜单",
         "excel_title": "NameNode"}
        , {"序号": "6", "model_key": "catalog", "key": "catalog_modify", "dao_name": "catalog_modify_dao",
           "file_name": "catalog_modify.html", "class_name": "CatalogModify", "api_name": "catalogModify",
           "primary_key": "catalog_modify_id", "business_type": "菜单修改", "excel_title": "Catalog Modify"}
        , {"序号": "7", "model_key": "catalog", "key": "catalog_delete", "dao_name": "catalog_delete_dao",
           "file_name": "catalog_delete.html", "class_name": "CatalogDelete", "api_name": "catalogDelete",
           "primary_key": "catalog_delete_id", "business_type": "菜单删除", "excel_title": "Catalog Delete"}
        , {"序号": "8", "model_key": "function", "key": "function", "dao_name": "function_dao",
           "file_name": "function.html", "class_name": "Function", "api_name": "function", "primary_key": "function_id",
           "business_type": "权限集", "excel_title": "Function Bas Information"}
        , {"序号": "9", "model_key": "function", "key": "function_permission", "dao_name": "function_permission_dao",
           "file_name": "function_permission.html", "class_name": "FunctionPermission",
           "api_name": "functionPermission", "primary_key": "function_permission_id", "business_type": "权限集权限点",
           "excel_title": "Function Permission"}
        , {"序号": "10", "model_key": "function", "key": "function_catalog", "dao_name": "function_catalog_dao",
           "file_name": "function_catalog.html", "class_name": "FunctionCatalog", "api_name": "functionCatalog",
           "primary_key": "function_catalog_id", "business_type": "权限集菜单", "excel_title": "Function Catalog"}
        , {"序号": "11", "model_key": "function", "key": "function_dimension", "dao_name": "function_dimension_dao",
           "file_name": "function_dimension.html", "class_name": "FunctionDimension", "api_name": "functionDimension",
           "primary_key": "function_dimension_id", "business_type": "权限集维度", "excel_title": "Function Dimension"}
        , {"序号": "12", "model_key": "role", "key": "role", "dao_name": "role_dao", "file_name": "role.html",
           "class_name": "Role", "api_name": "role", "primary_key": "role_id", "business_type": "角色",
           "excel_title": "Role"}
        , {"序号": "13", "model_key": "role", "key": "role_function", "dao_name": "role_function_dao",
           "file_name": "role_function.html", "class_name": "RoleFunction", "api_name": "roleFunction",
           "primary_key": "role_function_id", "business_type": "角色权限集", "excel_title": "Roles Function"}
        , {"序号": "14", "model_key": "role", "key": "role_function_delete", "dao_name": "role_function_delete_dao",
           "file_name": "role_function_delete.html", "class_name": "RoleFunctionDelete",
           "api_name": "roleFunctionDelete", "primary_key": "role_function_delete_id",
           "business_type": "取消角色权限集", "excel_title": "Roles Function Cancel"}
        , {"序号": "15", "model_key": "property", "key": "property_plan", "dao_name": "property_dao",
           "file_name": "property_plan.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-计划", "excel_title": "Property-plan"}
        , {"序号": "16", "model_key": "property", "key": "property_ins", "dao_name": "property_dao",
           "file_name": "property_ins.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-指令", "excel_title": "Property-ins"}
        , {"序号": "17", "model_key": "property", "key": "property_common", "dao_name": "property_dao",
           "file_name": "property_common.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-公共", "excel_title": "Property-common"}
        , {"序号": "18", "model_key": "property", "key": "property_data_plan", "dao_name": "property_dao",
           "file_name": "property_data_plan.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-监控", "excel_title": "Property-monitor"}
        , {"序号": "19", "model_key": "property", "key": "property_monitor", "dao_name": "property_dao",
           "file_name": "property_monitor.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-eod", "excel_title": "Property-eod"}
        , {"序号": "20", "model_key": "property", "key": "property_eod", "dao_name": "property_dao",
           "file_name": "property_eod.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-接入层", "excel_title": "Property-data cashplan"}
        , {"序号": "21", "model_key": "property", "key": "property_monitor_his", "dao_name": "property_dao",
           "file_name": "property_monitor_his.html", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-mon his", "excel_title": "Property-monitor his"}

    ]

    # 创建生成器并执行
    generator = FileGeneratorHtml()
    generator.generate_files(data_list)
